<template>
  <el-dialog v-if="load" title="更新授权" v-model="visible" append-to-body :close-on-click-modal="false" :z-index="2000" width="800px" @close="handleClose">
    <el-form ref="formRef" :model="form">
      <VSelect v-model="form.cur_ad_id" placeholder="请选择开发者" :options="options.developer" :clearable="false" class="w-60" @change="() => adChange(bind)" />
      <div v-for="(d, i) in form.auths" :key="i" class="flex gap-3 mt-3">
        <el-form-item :prop="['auths', i, 'checked']" :rules="[{ validator: (rule, val, cb) => validator(rule, val, cb, form.auths), trigger: 'change' }]">
          <el-checkbox :model-value="true" :disabled="true" :validate-event="false" class="w-20">{{codeMap[d.region_code]}}</el-checkbox>
          <!-- <el-checkbox v-else v-model="d.checked" :disabled="d.region_code === 'CN'" :validate-event="false"
            class="w-20">{{codeMap[d.region_code]}}</el-checkbox> -->
        </el-form-item>
        <el-form-item :prop="['auths', i, 'access_token']" :rules="[{ required: !!d.checked, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="d.access_token" placeholder="请输入区域token" :maxlength="200" class="w-60" />
        </el-form-item>
        <div class="leading-8">剩余天数</div>
        <el-form-item :prop="['auths', i, 'expiration_day']" :rules="[{ required: !!d.checked, message: '不能为空', trigger: 'change' }]">
          <el-input-number v-model="d.expiration_day" :controls="false" :min="-9999" :precision="0" placeholder="请输入" class="w-24" @change="val => dayChange(val, d)" />
        </el-form-item>
        <template v-if="d.expiration_day !== null">
          <div v-if="d.expiration_day < 0" class="leading-8 text-red-600">已过期 截止时间：{{ getDay(d.expiration_day) }}</div>
          <div v-else-if="d.expiration_day < 15" class="leading-8 text-yellow-600">即将过期 截止时间：{{ getDay(d.expiration_day) }}</div>
          <div v-else class="leading-8">截止时间：{{ getDay(d.expiration_day) }}</div>
        </template>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from './api'
import { ElMessage } from 'element-plus'
import XEUtils from 'xe-utils'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})
const formRef = ref()
const codeMap = ref({})

const adChange = () => {
  form.value.auths.forEach(d => {
    d.access_token = ''
    d.expiration_day = null
  })
}

const getDay = val => {
  if(val === undefined) return undefined
  return XEUtils.toDateString(XEUtils.getWhatDay(Date.now(), val), 'yyyy-MM-dd')
}

const dayChange = (val, d) => {
  if(val < 0 || !val) {
    d.expiration_day = 1
  }
}

const validator = (rule, val, cb, auths) => {
  if(auths.filter(d => d.checked)?.length < 2 && !val) {
    return cb(new Error('必选一个'))
  }
  cb()
}

// 打开弹窗
const open = async (account_name) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  visible.value = true
  codeMap.value = props.options.region_code.reduce((acc, cur) => {
    acc[cur.value] = cur.label
    return acc
  }, {})
  const res = await api.detail({account_name})
  form.value = { account_name, ...res.data }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const submit = () => {
  loadings.submit = true
  api.update(form.value).then(res => {
    ElMessage.success('操作成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>